package com.mass.waybill.records.controller;

import com.mass.core.sys.dict.model.SysDictVal;
import com.mass.core.sys.dict.service.SysDictValService;
import com.mass.core.sys.user.model.SysUser;
import com.mass.core.utils.AjaxResponse;
import com.mass.core.utils.DateUtils;
import com.mass.core.utils.ExcelUtil;
import com.mass.core.utils.NumberUtils;
import com.mass.waybill.order.model.WbShippingOrder;
import com.mass.waybill.records.model.WbSterilisationRecords;
import com.mass.waybill.records.service.WbSterilisationRecordsService;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: ZSX
 * @Description: 冲销记录
 */
@RestController
@RequestMapping("/wb/sterilisation/records")
public class WbSterilisationRecordsController {

    @Autowired
    private WbSterilisationRecordsService wbSterilisationRecordsService;
    @Autowired
    private SysDictValService sysDictValService;

    /**
     * 分页条件查询应收金额
     *
     * @param wbShippingOrder
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("/findReceivables")
    public AjaxResponse findReceivables(WbShippingOrder wbShippingOrder, Integer page, Integer limit) {
        return wbSterilisationRecordsService.findReceivables(wbShippingOrder, page, limit);
    }

    /**
     * 根据结算编号查询 订单冲销明细
     *
     * @param settlementNumber
     * @param isOrderCodeGroupBy 是否已订单编号分组查询冲销记录  1  分组(默认) 2 不分组
     * @return
     */
    @RequestMapping("/findOrderBySettlementNumber")
    public AjaxResponse findOrderBySettlementNumber(String settlementNumber, Integer isOrderCodeGroupBy) {
        List<WbShippingOrder> list = wbSterilisationRecordsService.findOrderBySettlementNumber(settlementNumber, isOrderCodeGroupBy);
        return AjaxResponse.success("ok", list, (long) list.size(), 1);
    }

    /**
     * 导出应收统计表
     *
     * @param wbShippingOrder
     * @param response
     */
    @RequestMapping("/export")
    public void export(WbShippingOrder wbShippingOrder, HttpServletResponse response) {
        //查询所有数据字典
        List<SysDictVal> sysDictValList = sysDictValService.getByTypeCode(null,null,null, null, null, null);
        //数据字典 Map  key  字典编码  value  字典值
        Map<String, String> dictMap = new HashMap<String, String>();
        for (SysDictVal sysDictVal : sysDictValList) {
            dictMap.put(sysDictVal.getValCode(), sysDictVal.getValName());
        }
        //查询应收信息
        List<WbShippingOrder> wbShippingOrderList = wbSterilisationRecordsService.findReceivablesAll(wbShippingOrder);
        //表头
        String[] titles = {"序号", "订单编号", "业务员", "下单日期", "发送日期", "业务类型", "品名", "箱型", "箱号", "发货单位", "装货地点", "发出", "到站", "收货人", "结算人", "货票号", "计费重量", "应收金额", "已收金额", "欠款"};
        if (!ObjectUtils.isEmpty(wbShippingOrder) && !ObjectUtils.isEmpty(wbShippingOrder.getStandby2()) && "2".equals(wbShippingOrder.getStandby2().trim())) {
            titles = new String[]{"序号", "订单编号", "业务员", "下单日期", "发送日期", "业务类型", "品名", "箱型", "箱号", "发货单位", "装货地点", "发出港", "到港", "收货人", "结算人", "货票号", "计费重量", "应收金额", "已收金额", "欠款"};
        }
        //文件名
        String fileName = "应收统计表";
        ServletOutputStream out = null;
        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet();
            int colNum = titles.length;
            int rowNO = 0;
            ExcelUtil.createExcelRow(workbook, sheet, rowNO, -1, colNum, "应收统计表");
            rowNO = rowNO + 1;
            ExcelUtil.createExcelRow(workbook, sheet, rowNO, 200, colNum, "制 表 日 期: " + (new SimpleDateFormat("yyyy-MM-dd")).format(new Date()), 180, "normal", "right");
            ++rowNO;
            ExcelUtil.createColumnHeader(workbook, sheet, rowNO, 300, titles);
            ++rowNO;
            String[][] strings = new String[wbShippingOrderList.size()][titles.length];
            //应收总金额   已收总金额
            Double accountsReceivableAmount = 0.00, sterilisationAmount = 0.00;
            for (int i = 0; i < wbShippingOrderList.size(); ++i) {
                WbShippingOrder order = wbShippingOrderList.get(i);
                strings[i][0] = (i + 1) + "";               //序号
                strings[i][1] = order.getOrderCode();        //订单编号
                strings[i][2] = order.getSalesman();        //业务员
                strings[i][3] = order.getOrderDate();       //下单日期
                strings[i][4] = order.getDateShipment();    //发送日期
                strings[i][5] = !ObjectUtils.isEmpty(dictMap.get(order.getBusinessTypes())) ? dictMap.get(order.getBusinessTypes()) : "—";               //业务类型
                strings[i][6] = !ObjectUtils.isEmpty(dictMap.get(order.getOfTheGoods())) ? dictMap.get(order.getOfTheGoods()) : "—";               //品名
                strings[i][7] = !ObjectUtils.isEmpty(dictMap.get(order.getaBox())) ? dictMap.get(order.getaBox()) : "—"; //箱型
                strings[i][8] = !ObjectUtils.isEmpty(order.getCartonNo()) ? order.getCartonNo() : "";               //箱号
                strings[i][9] = !ObjectUtils.isEmpty(dictMap.get(order.getDeliveryUnit())) ? dictMap.get(order.getDeliveryUnit()) : "—";//发货单位
                strings[i][10] = !ObjectUtils.isEmpty(dictMap.get(order.getStandby1())) ? dictMap.get(order.getStandby1()) : "—";//装货地点
                strings[i][11] = !ObjectUtils.isEmpty(dictMap.get(order.getaStation())) ? dictMap.get(order.getaStation()) : "—";///发出
                strings[i][12] = !ObjectUtils.isEmpty(dictMap.get(order.getArriveStation())) ? dictMap.get(order.getArriveStation()) : "—";               //到站
                strings[i][13] = !ObjectUtils.isEmpty(dictMap.get(order.getReceivingUnit())) ? dictMap.get(order.getReceivingUnit()) : "—";                  //收货人
                strings[i][14] = !ObjectUtils.isEmpty(dictMap.get(order.getSettlementPeople())) ? dictMap.get(order.getSettlementPeople()) : "—";                 //结算人
                strings[i][15] = !ObjectUtils.isEmpty(order.getGoodsWere()) ? order.getCartonNo() : "";  //货票号
                strings[i][16] = !ObjectUtils.isEmpty(order.getChargeableWeight()) ? order.getChargeableWeight() : ""; //计费重量
                strings[i][17] = String.format("%.2f", Double.parseDouble(order.getAccountsReceivableAmount().trim())); //应收金额
                accountsReceivableAmount = NumberUtils.add(accountsReceivableAmount, Double.parseDouble(order.getAccountsReceivableAmount().trim()));
                if (!ObjectUtils.isEmpty(order.getSterilisationAmount())) {
                    strings[i][18] = String.format("%.2f", Double.parseDouble(order.getSterilisationAmount().trim()));             //已收金额
                    double qian = NumberUtils.subtract(Double.parseDouble(order.getAccountsReceivableAmount().trim()), Double.parseDouble(order.getSterilisationAmount().trim()));  //欠款
                    strings[i][19] = String.format("%.2f", qian);              //欠款
                    sterilisationAmount = NumberUtils.add(sterilisationAmount, Double.parseDouble(order.getSterilisationAmount().trim()));
                } else {
                    strings[i][18] = "0.00";
                    strings[i][19] = strings[i][17];               //欠款
                }
            }
            sheet = ExcelUtil.createColumnData(workbook, sheet, rowNO, strings, wbShippingOrderList.size() + 3);
            //最后一行
            HSSFRow lastRow = sheet.createRow((short) (sheet.getLastRowNum() + 1));
            lastRow.createCell(1).setCellValue(new HSSFRichTextString("合计："));
            lastRow.createCell(17).setCellValue(new HSSFRichTextString(String.format("%.2f", accountsReceivableAmount)));
            lastRow.createCell(18).setCellValue(new HSSFRichTextString(String.format("%.2f", sterilisationAmount)));
            lastRow.createCell(19).setCellValue(new HSSFRichTextString(String.format("%.2f", NumberUtils.subtract(accountsReceivableAmount, sterilisationAmount))));
            // ExcelUtil.createSummaryRow(workbook, sheet, colNum, "行数合计：" + strings.length, 180, "normal", "right");

            fileName = fileName + (new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date());
            out = response.getOutputStream();
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".xls");
            workbook.write(out);
        } catch (Exception var35) {
            var35.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException var34) {
                var34.printStackTrace();
            }

        }
    }

    /**
     * 冲销
     *
     * @param wbSterilisationRecordsList
     * @return
     */
    @PostMapping("/insertBatch")
    public AjaxResponse insertBatch(@RequestBody List<WbSterilisationRecords> wbSterilisationRecordsList, HttpSession session) {
        String orderCode = "", batchNumber = "";
        Object object = session.getAttribute("sysUser");
        if (!ObjectUtils.isEmpty(object)) {
            SysUser sysUser = (SysUser) object;
            if (!ObjectUtils.isEmpty(wbSterilisationRecordsList)) {
                for (WbSterilisationRecords wbSterilisationRecords : wbSterilisationRecordsList) {
                    wbSterilisationRecords.setOperation(sysUser.getName());
                    wbSterilisationRecords.setOperatingTime(DateUtils.getDate("yyyy年MM月dd日 HH:mm"));
                }
            }
        } else {
            return AjaxResponse.success("未登录！");
        }
        return AjaxResponse.success(wbSterilisationRecordsService.insertBatch(wbSterilisationRecordsList));
    }

    @PostMapping("/findBySettlementNumber")
    public AjaxResponse findBySettlementNumber(String settlementNumber) {
        return AjaxResponse.success(wbSterilisationRecordsService.findBySettlementNumber(settlementNumber));
    }

    @PostMapping("/deleteRecords")
    public AjaxResponse deleteRecords(Long id) {
        return AjaxResponse.success(wbSterilisationRecordsService.deleteRecords(id));
    }

}
